﻿using System;
using System.Collections.Generic;
using System.Linq;
using IterationLife.System.Models;
using IterationLife.System.Repositories;
using Util.Datas.Ef;

namespace IterationLife.Datas.Repositories.Systems {
    /// <summary>
    /// 用户仓储
    /// </summary>
    public class UserRepository : RepositoryBase<User>, IUserRepository {
        /// <summary>
        /// 初始化用户仓储
        /// </summary>
        /// <param name="unitOfWork">工作单元</param>
        public UserRepository( IApplicationUnitOfWork unitOfWork ) : base( unitOfWork ) {
        }


        /// <summary>
        /// 获取启用用户集合
        /// </summary>
        public List<User> GetEnabledList() {
            return FindList( t => t.Enabled );
        }

        /// <summary>
        /// 获取用户编号
        /// </summary>
        /// <param name="userName">用户名</param>
        public Guid GetUserId( string userName ) {
            var user = Find().FirstOrDefault( t => t.UserName == userName );
            return user == null ? Guid.Empty : user.Id;
        }

        ///// <summary>
        ///// 根据Token获取用户
        ///// </summary>
        ///// <param name="token">安全令牌</param>
        //public User GetUserByToken( string token ) {
        //    return Single( t => t.Token == token );
        //}

        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="userName">用户名</param>
        public bool IsUserNameExisted( string userName ) {
            return Single( t => t.UserName == userName ) != null;
        }

        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="id">编号</param>
        public bool IsUserNameExisted( string userName, Guid id ) {
            return Single( t => t.UserName == userName && t.Id != id ) != null;
        }

        public bool IsPhoneNumberExisted(string phoneNumber)
        {
            return Single(t => t.Mobile == phoneNumber) != null;
        }

        public bool IsPhoneNumberExisted(string phoneNumber, Guid id)
        {
            return Single(t => t.Mobile == phoneNumber && t.Id != id) != null;
        }

        public bool IsEmailExisted(string email)
        {
            return Single(t => t.Email == email) != null;
        }

        public bool IsEmailExisted(string email, Guid id)
        {
            return Single(t => t.Email == email && t.Id != id) != null;
        }
    }
}
